<template>
  <div class="go-top">
    <img
      src="../assets/images/use/use-top.png"
      @click="backTop"
      alt="返回顶部"
    />
  </div>
</template>

<script>
export default {
  name: "goTop",
  data() {
    return {
      topShow: false, //记录当前返回顶部标志的可视状态
      scrollTop: 0, //当前滚动位置
    };
  },
  mounted() {
    window.addEventListener("scroll", this.scrollToTop); //监听滚动条
  },
  destroyed() {
    window.removeEventListener("scroll", this.scrollToTop); //移除滚动条监听
  },
  methods: {
    // 点击图片回到顶部方法，加计时器是为了过渡顺滑
    backTop() {
      let that = this;
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          that.scrollTop + ispeed;
        if (that.scrollTop === 0) {
          clearInterval(timer);
        }
      }, 16);
    },

    // 为了计算距离顶部的高度，当高度大于200显示回顶部图标，小于200则隐藏
    scrollToTop() {
      let that = this;
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      that.scrollTop = scrollTop;
      if (that.scrollTop > 200) {
        that.btnFlag = true;
      } else {
        that.btnFlag = false;
      }
    },
  },
};
</script>

<style lang="scss">
.go-top {
  position: absolute;
  bottom: fh(20vh, pc);
  right: fw(-20vw, pc);
  transform: translateX(100%);
  width: fw(80vw, pc);
  background-color: $zh;
  img {
    width: fw(80vw, pc);
  }
  &:hover {
    opacity: 0.8;
    cursor: pointer;
  }
}
</style>
